#! /usr/bin/perl

#also enable strict mode
use strict;

#use the HMTLSubs package and DBQueries package
use HTMLSubs;
use DBQueries;
use CGI;
use ValidationSubs;

#start by obtaining the input so that the username can be determined
my $input = obtain_input();


#ensure that input is not blank which would mean that the site is illegally accessed
if(length($input) == 0){
	
	#if so, redirect to login
	print CGI -> redirect("login.pl.cgi");
}

#call method to split the full string into a hash of individual variables
#this subroutine returns a reference to the submitted info hash
my $ref_submitted_info = HTMLSubs->decode_input($input);

#dereference the submitted info
my %submitted_info = %$ref_submitted_info;

#declare fields
my $username;
my $file_id;
my $file_name;

#now determine if a new name was submitted or if the information is passed to the script for the first time
#if called initially, only the username and file id will be passed 
#if the only input is of size 2 
if(scalar(keys %submitted_info) == 2){
	
	#in this case the user has not updated any infomration yet and the update page will be displayed for the first time
	#therefore isolate the passed information
	$username = $submitted_info{'username'};
	$file_id = $submitted_info{'fileID'};
	$file_name = DBQueries::getFileName($file_id);
	
	#now display the submission form with no error message
	display_rename_group();
}
#otherwise we know that a rename was submitted so determine if valid
else{
	
	#now call subroutine to process input
	#pass this sub the reference to submitted info
	#this subroutine will take control of the flow of the script and determine what actions to further take
	process_update($ref_submitted_info);
}

#subroutine to both determine the validity of the users input and to process the submission
#this subroutine will call a subroutine to determine if the field was entered correctly
sub process_update{
	
	#obtain user information from parameter
	my $ref_submitted_info = $_[0];
	
	#dereference hash to local variable
	my %submitted_info = %$ref_submitted_info;
	
	#obtain username
	$username = $submitted_info{'username'};
	$file_id = $submitted_info{'fileID'};
	
	#obtain new name
	my $updated_name = $submitted_info{'newFileName'};
	
	
	#ensure the submission is valid
	if((ValidationSubs -> validate_file_name($username, $updated_name)) == 1){
		
		#add underscores to file names
		$updated_name =~ s/ /_/g;
		
		#update the DB
		DBQueries::updateFileName($file_id, $updated_name);
		
		#call method to show the success page
		show_success($username, $file_id);
		
	}
	#otherwise the new name is already taken
	else{
		
		#produce appropriate error message and redisplay submission
		my $error_message = "<h4><font color=\"red\">You already own a file with that name or it is not a .txt file. Please try again.</font></h4>";
		
		#now redisplay
		display_rename_group($error_message);
	}
}

#subroutine that is called whenever the user succesfully renames a file
#this subroutine will display a success message to the user before redirecting to the main window
#this sub is passed two parameter, the username, and the file ID
sub show_success{
	
	#obtain parameter
	my $username = $_[0];
	my $file_id = $_[1];
	
	#call method to display html beginnign
	HTMLSubs->generate_html_beginning("Successfully Renamed File!");
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "Successfully Renamed", $username);
	
	print <<END_HTML;
	
	<!--now display the message to the user-->
	<h4>Please return to your profile for further action.</h4>
	<br>
	
END_HTML

	#create hash for button
	my %parameter_hash;
	$parameter_hash{'username'} = $username;
	$parameter_hash{'fileSelected'} = DBQueries::getFileName($file_id);
	
	#call subroutine to display button that returns the user to the profile
	HTMLSubs -> generate_html_button("profile.pl.cgi", "Go To profile", \%parameter_hash);

	#now call method to produce closing html tags
	HTMLSubs->generate_html_end();
}

#subroutine to display the update page
#this subroutine accepts an error message as a parameter to be displayed above the submission form
sub display_rename_group{
	
	#obtain potential messages
	my $error_text = $_[0] || "";
	
	#call routine to display beginning of html
	HTMLSubs -> generate_html_beginning("Rename Group");
	
	#call the subroutine to create the html code for the actual form and pass it the correct entries reference
	generate_rename_html($ENV{'SCRIPT_NAME'}, $error_text);
	
	#call the subroutine to end the html code
	HTMLSubs -> generate_html_end();
}

#subroutine to create the html password form
#this sub is passed the name of the target for the form
sub generate_rename_html{
	
	#obtain target
	my $form_target = $_[0];
	
	#get error message
	my $error_text = $_[1];
	
	#call sub to print header
	HTMLSubs -> generate_display_head("Document Management System", "Rename $file_name", $username);
	
	print <<END_HTML;
	
	<!--now move to the main content of the site-->
	<div class="content">
END_HTML

	#print any potential error messages passed to the subroutine and ensure that not too many <br> tags are printed
	#by determining if the length of the text is 0 or not
	if(length($error_text) != 0){
		print "$error_text<br>";
	}
	
	print <<END_HTML;
	<!-- place form in table for appearance formatting-->
	<table>
		<form action="$form_target" method=POST>
		<!--old name-->
		<tr>
			<td><p>Current Name:</p></td>
			<td><input disabled type="text" name="oldName" value="$file_name"></td>
		</tr>
		<!--new name-->
		<tr>
			<td><p>New name (must end in .txt):</p></td>
			<td><input type="text" name="newFileName"></td>
		</tr>
		
		<!-- now create a hidden field that resubmits the usernmae so that the script knows what user is being passed back-->
		<input type="hidden" name="username" value="$username">
		
		<!-- now create a hidden field that resubmits the file ID so that the script knows what file is being passed back-->
		<input type="hidden" name="fileID" value="$file_id">
		
		<tr>
			<td><input type="submit" value="Submit"></form>
END_HTML
			#call subroutine to crate a cancel button
			#this subroutine takes the name of a script and the value of the button 
			
			
			#create a hash containing only the username key/value pair to be passed to the button creation subroutine
			my %parameter_hash;
			$parameter_hash{'username'} = $username;
			$parameter_hash{'fileSelected'} = $file_name;
			
			HTMLSubs -> generate_html_button("profile.pl.cgi", "Cancel", \%parameter_hash);
			
			#print remainder of html
			print <<END_HTML;
			</td>
		</tr>
	</table>
END_HTML
	
}	

#subroutine to obtain and determine what information is passed to the script
#to make this more universal, both GET and POST methods are accepted 
#this reads input for both GET and POST
sub obtain_input{

	#declare scalar to hold passed information
	my $input;

	#now retrieve the input through either get or post
	#change the case of request method
	$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;

	#if post use STDIN
	if ($ENV{'REQUEST_METHOD'} eq "POST"){
		read(STDIN, $input, $ENV{'CONTENT_LENGTH'});

		#exchange plus signs to spaces
		$input =~ s/\+/ /;

		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	#otherwise the env hash
	else{
		$input = $ENV{'QUERY_STRING'};
		
		#exchange plus signs to spaces
		$input =~ s/\+/ /;
		
		#deal with special characters using the substitution sample provided
		$input =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;
	}
	
	#now return the correct input
	return $input;	
}
